package com.tvunetworks.center.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.user.constant.UserConstant;
import com.tvunetworks.center.user.mapper.FeatureMapper;
import com.tvunetworks.center.user.model.Feature;
import com.tvunetworks.center.user.model.MenuBar;
import com.tvunetworks.center.user.model.User;
import com.tvunetworks.center.user.model.param.AddFeatureParam;
import com.tvunetworks.center.user.model.vo.FeatureVo;
import com.tvunetworks.center.user.service.FeatureService;
import com.tvunetworks.center.user.service.MenuBarService;
import com.tvunetworks.center.user.service.UserFeatureService;
import com.tvunetworks.center.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: tvucc-aggregator
 * @description: FeatureServiceImpl
 * @author lebronchen
 * @create: 2019-06-10 15:59
 **/
@Service
@Slf4j
public class FeatureServiceImpl extends BaseService<Feature> implements FeatureService {

    @Autowired
    private FeatureMapper featureMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private MenuBarService menuBarService;
    @Autowired
    private UserFeatureService userFeatureService;

    @Override
    @Transactional
    public int addFeature(AddFeatureParam param) {
        boolean exist = this.featureExist(param.getFeature());
        if (exist) {
            // feature 已存在
            return 1;
        }

        Feature feature = new Feature();
        BeanUtils.copyProperties(param, feature);
        if (feature.getOrderNo() == null) {
            int maxOrderNo = featureMapper.getMaxOrderNo();
            feature.setOrderNo(maxOrderNo + 10);
        }
        super.insert(feature);
        return 0;
    }

    @Override
    @Transactional
    public int updateFeature(String id, AddFeatureParam param) {
        Feature exist = this.getById(id);
        if (exist == null) {
            // feature 不存在
            return 1;
        }
        Feature feature = this.getByFeature(param.getFeature());
        if (feature != null && !StringUtils.equals(id, feature.getId())) {
            // feature 重复
            return 2;
        }
        BeanUtils.copyProperties(param, exist);
        super.updateSelective(exist);
        return 0;
    }

    @Override
    @Transactional
    public int deleteFeature(String id) {
        Feature exist = this.getById(id);
        if (exist == null) {
            // feature 不存在
            return 1;
        }
        List<MenuBar> menuBars = menuBarService.listByFeatureId(id);
        if (!CollectionUtils.isEmpty(menuBars)) {
            // 存在menu使用当前feature
            return 2;
        }
        super.deleteLogicById(id);
        userFeatureService.removeUserFeatureByFeatureId(id);
        return 0;
    }

    private boolean featureExist(String feature){
        Feature exist = this.getByFeature(feature);
        if (exist != null) {
            return true;
        }
        return false;
    }

    @Override
    public Feature getByFeature(String feature) {
        Feature record = new Feature().setFeature(feature);
        return super.selectExistOne(record);
    }

    @Override
    public Feature getById(String id) {
        return super.selectExistByPrimaryKey(id);
    }

    @Override
    public List<FeatureVo> listAll() {
        return featureMapper.listAll();
    }

    @Override
    public List<FeatureVo> listAdminAutoOwnFeature() {
        return featureMapper.listAdminAutoOwnFeature();
    }

    @Override
    public List<FeatureVo> listNotAdminAutoOwnFeature() {
        return featureMapper.listNotAdminAutoOwnFeature();
    }

    @Override
    public Map<String, List<FeatureVo>> listFeatureForCreate(LoginUser loginUser, String role, String ownerId) {
        return this.listCanModifyFeature(loginUser, null, role, ownerId);
    }

    @Override
    public Map<String, List<FeatureVo>> listFeatureForModify(LoginUser loginUser, String modifyUserId) {
        return this.listCanModifyFeature(loginUser, modifyUserId, null, null);
    }

    @Override
    public PageInfo<FeatureVo> pageFeature(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<FeatureVo> list = featureMapper.listAll();
        return new PageInfo<>(list);
    }

    private Map<String, List<FeatureVo>> listCanModifyFeature(LoginUser loginUser, String modifyUserId, String role, String ownerId) {
        boolean forCreateUser = StringUtils.isBlank(modifyUserId);
        String loginUserId = loginUser.getId();
        String loginUserRole = loginUser.getRole();
        Map<String, List<FeatureVo>> map = new HashMap<>();
        map.put(UserConstant.Feature.ADMIN_AUTO_OWN_KEY, new ArrayList<>());
        map.put(UserConstant.Feature.NOT_ADMIN_AUTO_OWN_KEY, new ArrayList<>());

        String adminUserId = null;
        if (!forCreateUser) {
            User modifyUser = userService.getById(modifyUserId);
            if (modifyUser == null) {
                return map;
            }
            role = modifyUser.getRole();

            adminUserId = modifyUser.getUserParentId();
        }

        if (StringUtils.equals(loginUserRole, LocalConstant.UserRole.SUPPORT)) {
            // 登陆用户为support
            if (StringUtils.equals(role, LocalConstant.UserRole.ADMIN)) {
                // Support为admin分配权限，列出所有非admin自身拥有的权限
                List<FeatureVo> featureVos = featureMapper.listNotAdminAutoOwnFeature();
                if (featureVos != null && featureVos.size() > 0) {
                    map.put(UserConstant.Feature.NOT_ADMIN_AUTO_OWN_KEY, featureVos);
                }
                return map;
            } else {
                if (forCreateUser) {
                    // 列出admin默认拥有的权限
                    adminUserId = ownerId;
                } else {
                    // Support为user分配权限
                    // 等同于user父亲admin账户为user账户分配权限
                    if (StringUtils.isBlank(adminUserId)) {
                        // 列出admin默认拥有的权限
                        List<FeatureVo> adminAutoOwnFeatures = featureMapper.listAdminAutoOwnFeature();
                        if (adminAutoOwnFeatures == null || adminAutoOwnFeatures.size() == 0) {
                            adminAutoOwnFeatures = new ArrayList<>();
                        }
                        map.put(UserConstant.Feature.ADMIN_AUTO_OWN_KEY, adminAutoOwnFeatures);
                        return map;
                    }
                }
            }
        } else {
            // 登陆用户为admin
            // 列出admin默认拥有的权限和当前admin自身有的权限
            adminUserId = loginUserId;
        }

        // 登陆用户为admin
        // 列出admin默认拥有的权限
        List<FeatureVo> adminAutoOwnFeatures = featureMapper.listAdminAutoOwnFeature();
        if (adminAutoOwnFeatures == null || adminAutoOwnFeatures.size() == 0) {
            adminAutoOwnFeatures = new ArrayList<>();
        }
        map.put(UserConstant.Feature.ADMIN_AUTO_OWN_KEY, adminAutoOwnFeatures);
        // 列出当前admin用户自生拥有的 非admin自身拥有的feature
        List<FeatureVo> userOenFeatures = featureMapper.listUserNotAdminAutoOwnFeature(adminUserId);
        if (userOenFeatures == null || userOenFeatures.size() == 0) {
            userOenFeatures = new ArrayList<>();
        }
        map.put(UserConstant.Feature.NOT_ADMIN_AUTO_OWN_KEY, userOenFeatures);
        return map;
    }
}
